//
//  ArticleDetailMengwenViewController.m
//  Adorable_Things
//
//  Created by lanou on 16/1/12.
//  Copyright © 2016年 Banana Inc. All rights reserved.
//

#import "ArticleDetailMengwenViewController.h"
#import "ArticleDetailMengwenModel.h"
#import "ArticleDetailMengwenTableViewCell.h"
#import "ArticleDetailViewController.h"
#import "ArticleDetailHeaderView.h"
#import "TTNavView.h"
#import "ATMainDetailViewController.h"
#import "ATShareFootView.h"
#import "UMSocial.h"

#define kArticleMengwenUrl @"http://api.menghuoapp.com/v1/post/detail"

@interface ArticleDetailMengwenViewController () <UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) ArticleDetailHeaderView *headerView;
@property (nonatomic, strong) TTNavView *navView;
@property (nonatomic, strong) NSString *shareUrl;

@end

@implementation ArticleDetailMengwenViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 580;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self setUpData];
    _dataArr = [NSMutableArray array];
    
    [self addHeaderView];
}

- (void)setUpData
{
    ATUserManager *atManager = [ATUserManager shareManager];
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"auth_token"] = atManager.auth_token;
    parDic[@"post_id"] = self.ID;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:kArticleMengwenUrl parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.url = responseObject[@"data"][@"pic_url"];
        self.headerTitle = responseObject[@"data"][@"title"];
        self.intro = responseObject[@"data"][@"intro"];
        self.summary = responseObject[@"data"][@"summary"];
        self.topic_ID = responseObject[@"data"][@"post_type"];
        
        NSArray *content_itemsArr = responseObject[@"data"][@"content_items"];
        
        for (NSDictionary *oneDic in content_itemsArr) {
            ArticleDetailMengwenModel *model = [[ArticleDetailMengwenModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            self.shareUrl = model.url;
            [_dataArr addObject:model];
        }
        [_tableView reloadData];
        self.block();
        self.IDBlock(self.topic_ID);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败");
    }];
}

- (void)addHeaderView
{
    self.headerView = [[ArticleDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 420)];
    self.tableView.tableHeaderView = self.headerView;
    __weak ArticleDetailMengwenViewController *mySelf = self;
    self.block = ^ void(){
        [mySelf.headerView.headerImageV sd_setImageWithURL:[NSURL URLWithString:mySelf.url]];
        mySelf.headerView.headerIntroLabel.text = mySelf.intro;
        mySelf.headerView.headerIntroLabel.font = [UIFont systemFontOfSize:19];
        mySelf.headerView.headerTitleLabel.text = mySelf.headerTitle;
        mySelf.headerView.headerTitleLabel.font = [UIFont systemFontOfSize:20];
    };
    
    ATShareFootView *footView = [[ATShareFootView alloc]initWithFrame:CGRectMake(0, 30, kWidth , 100)];
    
    _tableView.tableFooterView = footView;
    
    [footView.weixinBut addTarget:self action:@selector(weixinAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [footView.friendBut addTarget:self action:@selector(friendButAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [footView.weibo addTarget:self action:@selector(weiboAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [footView.QQBut addTarget:self action:@selector(QQButAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [footView.QQzoneBut addTarget:self action:@selector(QQzoneButAction:) forControlEvents:(UIControlEventTouchUpInside)];

}

- (void)weixinAction:(UIButton *)button
{
    
    NSString *str = [NSString stringWithFormat:@"我在Adorable_Things关注了%@",self.headerTitle];
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatSession] content:str image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];
    
}

- (void)friendButAction:(UIButton *)button
{
    NSString *str = [NSString stringWithFormat:@"我在Adorable_Things关注了%@",self.headerTitle];
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatTimeline] content:str image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];
}

- (void)weiboAction:(UIButton *)button
{
    NSString *str = [NSString stringWithFormat:@"我在Adorable_Things关注了%@",self.headerTitle];
    [[UMSocialControllerService defaultControllerService] setShareText:str shareImage:[UIImage imageNamed:@"icon_120"] socialUIDelegate:nil];        //设置分享内容和回调对象
    [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina].snsClickHandler(self,[UMSocialControllerService defaultControllerService],YES);
    
}

- (void)QQButAction:(UIButton *)button
{
    NSString *str = [NSString stringWithFormat:@"我在Adorable_Things关注了%@",self.headerTitle];
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQQ] content:str image:[UIImage imageNamed:@"L108"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];
}

- (void)QQzoneButAction:(UIButton *)button
{
    NSString *str = [NSString stringWithFormat:@"我在Adorable_Things关注了%@",self.headerTitle];
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQzone] content:str image:[UIImage imageNamed:@"L108"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ArticleDetailMengwenTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MengwenTableViewCell"];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ArticleDetailMengwenTableViewCell" owner:self options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    ArticleDetailMengwenModel *model = _dataArr[indexPath.row];
    [cell.imageV sd_setImageWithURL:[NSURL URLWithString:model.pic_urls.firstObject]];
    cell.titleLabel.text = model.title;
    cell.titleLabel.font = [UIFont systemFontOfSize:18];
    cell.introLabel.text = model.intro;
    cell.introLabel.numberOfLines = 0;
    cell.introLabel.font = [UIFont systemFontOfSize:19];
    [cell.favorButton setImage:[UIImage imageNamed:@"iconfont-tubiao"] forState:(UIControlStateNormal)];
    [cell.favorButton setTintColor:[UIColor lightGrayColor]];
    cell.favorLabel.text = [NSString stringWithFormat:@"%@", model.favorite_num];
    [cell.commentButton setImage:[UIImage imageNamed:@"iconfont-pinglunnc"] forState:(UIControlStateNormal)];
    [cell.commentButton setTintColor:[UIColor lightGrayColor]];
    cell.commentLabel.text = [NSString stringWithFormat:@"%@", model.comment_num];
    NSString *str = [NSString stringWithFormat:@"￥%.2f >", model.price];
    [cell.priceLabel setTitle:str forState:(UIControlStateNormal)];
    [cell.priceLabel addTarget:self action:@selector(priceLabelClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.priceLabel setTintColor:[UIColor whiteColor]];
    cell.priceLabel.backgroundColor = [UIColor redColor];
    cell.priceLabel.layer.cornerRadius = 15;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ATMainDetailViewController *atMainDetailVC = [[ATMainDetailViewController alloc] init];
    ArticleDetailMengwenModel *model = _dataArr[indexPath.row];
    atMainDetailVC.item_id = model.item_id;
    atMainDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:atMainDetailVC animated:YES];
}

- (void)priceLabelClick:(UIButton *)button
{
    ArticleDetailMengwenTableViewCell *cell = (ArticleDetailMengwenTableViewCell *)[[button superview] superview];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    ArticleDetailMengwenModel *model = self.dataArr[indexPath.row];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:model.click_url]];
}

- (void)rightButtonClick:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
   [super viewWillAppear:animated];
   self.navigationController.navigationBarHidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
